<template>
    <div>
        <!--面包屑导航区域-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!--卡片视图区域-->
        <el-card class="box-card">           
            <!--表格头-->
            <el-row :gutter="30">
            <el-col :span="8">
                <!--搜索与添加区域-->
                <el-input placeholder="请输入内容" clearable @clear="getUserList"
                v-model="queryInfo.query">
                    <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                </el-input>
            </el-col>
            <el-col :span="4">
                <el-button type="primary" @click="addDiglogVisble = true">添加用户</el-button>
            </el-col>
            </el-row>
            <!--用户列表区域-->
            <el-table :data="userList" border stripe >
                <el-table-column type=index label="#"></el-table-column>
                <el-table-column prop="id" label="ID" ></el-table-column>
                <el-table-column prop="username" label="姓名"></el-table-column>
                <el-table-column prop="email" label="邮件" ></el-table-column>
                <el-table-column prop="mobile" label="电话" > </el-table-column>
                <el-table-column prop="role_name" label="角色"> </el-table-column>
                <el-table-column  label="状态"> 
                     <template slot-scope="scope">
                         <el-switch
                            v-model="scope.row.mg_state"
                            active-color="#13ce66"
                            inactive-color="#ff4949"
                            @change="userStateChange(scope.row)">                      
                         </el-switch>
                    </template>
                </el-table-column>
                <el-table-column  label="操作" width='200px'>
                <template slot-scope="scope">
                    <!--修改按钮-->
                  <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)"></el-button>
                  <!--删除按钮-->
                  <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserByid(scope.row.id)"></el-button>

                 <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable='false'>
                 <el-button type="warning" icon="el-icon-setting" size="mini" @click="assignRoles(scope.row)"></el-button>
                </el-tooltip>
                </template>
                </el-table-column>                
            </el-table>
        <!--分页区域-->
           <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page='queryInfo.pagenum'
            :page-sizes="[10, 20, 50, 2,1]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
            </el-pagination>           
        </el-card>

     <!--添加用户对话框-->   
     <el-dialog
        title="添加用户"
        :visible.sync="addDiglogVisble"
        width="50%"
        @close="clearForm" >
        <!--内容主体区域-->
        <el-form :model="addUserFrom" :rules="addFromRules" ref="userForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="姓名" prop="username">
            <el-input v-model="addUserFrom.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
            <el-input v-model="addUserFrom.password" ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserFrom.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
            <el-input v-model="addUserFrom.mobile"></el-input>
        </el-form-item>
        </el-form>
         <!--底部区域-->
        <span slot="footer" class="dialog-footer">
            <el-button @click="addDiglogVisble = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
     </el-dialog>

     <!--修改用户对话框-->
        <el-dialog
            title="修改用户"
            :visible.sync="editDiglogVisble"
            width="50%"
            @close="clearFormEdit">
            <!--内容主体区域-->
            <el-form :model="editUserFrom" :rules="addFromRules" ref="userFormEdit" label-width="70px" class="demo-ruleForm">
            <el-form-item label="姓名" prop="username">
                <el-input v-model="editUserFrom.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="editUserFrom.email"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="mobile">
                <el-input v-model="editUserFrom.mobile"></el-input>
            </el-form-item>
            </el-form>
            <!--底部区域-->
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDiglogVisble = false">取 消</el-button>
                <el-button type="primary" @click="editUser">确 定</el-button>
            </span>
        </el-dialog>

        <!--用户分配角色的对话框  -->
         <el-dialog
            title="角色分配"
            :visible.sync="showSetRoletDialogVisible"
            width="50%"
            @close="showSetRoletDialogClosed"
            >
            <div>
                <p>当前用户：{{userInfo.username}}</p>
                <p>当前角色：{{userInfo.role_name}}</p>
                <p>选择角色: <el-select v-model="selectRoleId" placeholder="请选择角色">
                    <el-option
                    v-for="item in roleList"
                    :key="item.id"
                    :label="item.roleName"
                    :value="item.id">
                    </el-option>
                </el-select>
                </p>
                
            </div>
            
           <!-- 底部 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="showSetRoletDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveRoleInfo(userInfo)">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>
<script>
export default {
    data() {
        return {
            queryInfo:{
            //获取用户列表的参数对象
            query:'',
            //当前页
            pagenum:1,
            //当前页每页数据
            pagesize:5
            },
            userList:[],
            total:0,
            //控制添加用户属性框
            addDiglogVisble:false,
            //控制修改用户属性框
            editDiglogVisble:false,
            //添加的用户验证
            addUserFrom:{
                username:'',
                password:'',
                email:'',
                mobile:'',
                
            },
            //编辑用户数据
               editUserFrom:{ },
            //添加的表单规则验证
            addFromRules:{
                username:[
                   { required: true, message: '请输入用户名称', trigger: 'blur' },
                   { min: 3, max: 10, message: '用户名长度在 3 到10 个字符', trigger: 'blur' }
                ],
                 password:[
                   { required: true, message: '请输入密码', trigger: 'blur' },
                   { min: 6, max: 15, message: '密码长度在 6 到15 个字符', trigger: 'blur' }
                ],email:[
                   { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']},
                ],mobile: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    {
                    pattern: /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/, message: '请输入正确的手机号码或者座机号',},
                    ],

                
            },
            //控制角色分配对话框
            showSetRoletDialogVisible:false,
            //用户信息
            userInfo:{},
            //角色列表
            roleList:[],
            //已选中的角色id
            selectRoleId:''

        }
    },
    created() {
        //获取数据列表
        this.getUserList()
    },
    methods: {
      async  getUserList(){
      const {data:res}   =  await this.$http.get(
                'users', //路径
                {params:this.queryInfo} //参数
            );
            console.log(res);
            if(res.meta.status!==200){
                return this.$message.error("获取用户列表失败");
            }
            this.userList=res.data.users;
            this.total=res.data.total;
        },
        //监听最新的pageSize
        handleSizeChange(newSize){
            console.log(newSize)
             this.queryInfo.pagesize=newSize;
             this.getUserList();   
        },
        //监听页码值
        handleCurrentChange(newPage){
            console.log(newPage)
            this.queryInfo.pagenum=newPage;
            this.getUserList();
        },
        //修改用户状态
      async  userStateChange(userInfo){
         console.log(userInfo)

         const {data:res} = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`);
             console.log(res)
            if(res.meta.status!=200){
                userInfo.mg_state =!userList.mg_state;
                return this.$message.error("更新用户状态失败");
            }
             return this.$message.success(res.meta.msg);
       },
       //监听表单关闭事件，清空数据
       clearForm(){
            this.$refs.userForm.resetFields();//重置表单
       },
        //监听表单关闭事件，清空数据
       clearFormEdit(){
            this.$refs.userFormEdit.resetFields();//重置表单
       },
       //点击确认验证信息
       addUser(){
            this.$refs.userForm.validate(async valid=>{
                console.log(valid);
                //提交数据
                if(valid){
                  const {data:res} = await this.$http.post('users',this.addUserFrom);
                  console.log(res)
                    if(res.meta.status==201){
                         this.$message.success(res.meta.msg);
                        //隐藏添加框
                        this.addDiglogVisble=false;
                        //刷新列表
                        this.getUserList()
                    }else{
                         this.$message.error(res.meta.msg);
                            //隐藏添加框
                        this.addDiglogVisble=false;
                    }
                }
                return;
            })
       },
       //点击修改用户
       showEditDialog(user){
            this.editDiglogVisble=true;
            this.editUserFrom=user;
       },
       //确认修改
       editUser(){
            this.$refs.userFormEdit.validate(async valid=>{
                   if(!valid) return
                   //发起数据请求
             const {data:res} =    await this.$http.put(
                     'users/'+this.editUserFrom.id,
                     {email:this.editUserFrom.username,
                     mobile:this.editUserFrom.mobile }
                 );  
                console.log(res)
               if(res.meta.status==200){
                         this.$message.success(res.meta.msg);
                        //隐藏添加框
                        this.editDiglogVisble=false;
                        //刷新列表
                        this.getUserList()
                    }else{
                         this.$message.error(res.meta.msg);
                            //隐藏添加框
                        this.editDiglogVisble=false;
                    }
                 });    
       },
        //删除数据
       removeUserByid(id){
     //确认删除则返回字符串 confirm;点击取消则报错（可使用catch 捕获错误）
          this.$confirm('正在删除用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }).then(async  () => {
                   //确认提交     
            //   const {data:res} =  this.$http.delete("users/"+id)
            //     if(res.meta.status!=200){
            //         this.$message.error("删除失败");
            //     }   
               

               
             await this.delectUser("users/"+id);
               
            

                }).catch(() => {

                this.$message({ type: 'info',message: '已取消删除' });          
              });
           
        
                    
        },
        //删除方法
        delectUser(url){
              this.$my_http({
                    method:"delete",
                    url:url,

                }).then(res => {
                    if(res.data.meta.status != 200){
                      this.$message.error("删除失败");
                    }else{  
                     this.$message({ type: 'success', message: '删除成功!'});
                    //刷新列表
                 this.getUserList();
                 }
                }) 
        },
        //给用户分配角色
        assignRoles(user){
            this.userInfo =user;//赋值
            //获取所有角色列表
            this.$my_http({
                    method:"get",
                    url:'roles',
                }).then(res => {
                    if(res.data.meta.status != 200){
                      this.$message.error("获取角色列表失败");
                    }else{  
                    //赋值
                    this.roleList=res.data.data
                 }
                }) 

            this.showSetRoletDialogVisible=true;//打开对话框

        },
        //保存用户分配的角色
        saveRoleInfo(userinfo){
            //没有选择角色
            if(!this.selectRoleId){
            return this.$message.error("请选择角色");
            }
               //角色授权 
             this.$my_http({
                    method:"put",
                    //使用模板``可以避免数字别转为字符串
                    url:`users/${userinfo.id}/role`,
                    data:{
                        rid:this.selectRoleId
                    }
                }).then(res => {
                    console.log(res.data)
                    if(res.data.meta.status != 200){
                      this.$message.error(res.data.meta.msg);
                    }else{  
                     //刷新列表
                    this.getUserList()
                    this.$message.success(res.data.meta.msg);
                    this.showSetRoletDialogVisible=false
                 }
                }) 

        },
        //监听分配角色对话框关闭事件
        showSetRoletDialogClosed(){
            this.selectRoleId='';
            this.userInfo={}
          
        }

    },
}
</script>
<style lang='less' scoped>

</style>